package com.java.config;

import java.lang.reflect.Method;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import com.google.common.collect.Maps;

/**
 * <p>
 * Redis 相关自定义配置,<br/>
 * 1. 设置Key 序列化方式为string <br/>
 * 2. 设置Cache 带前缀并自动加载缓存失效时间
 * </p>
 * 
 * @Author Vigor Yuan
 */
@Configuration
@EnableCaching
public class RedisConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "spring.redis")
    JedisConnectionFactory jedisConnectionFactory() {
        return new JedisConnectionFactory();
    }

    @Bean
    RedisTemplate<String, Object> redisTemplate() {
        final RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(jedisConnectionFactory());
        template.setKeySerializer(template.getStringSerializer());
        return template;
    }

    @ConfigurationProperties(prefix = "sys.redis.cache")
    @Bean(name = "redisCacheMap")
    Map<String, Integer> cacheMap() {
        return Maps.newHashMap();
    }

    @Bean
    CacheManager cacheManager() {
        Map<String, Long> cacheMap = Maps.newHashMap();
        Map<String, Integer> map = cacheMap();
        for (String key : map.keySet()) {
            cacheMap.put(key, new Long(map.get(key) + ""));
        }
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
        redisCacheManager.setExpires(cacheMap);
        redisCacheManager.setUsePrefix(true);
        redisCacheManager.setDefaultExpiration(3000);
        return redisCacheManager;
    }

    /**
     * spring @Cacheable 参数key必须是str, int型无法作为key 通过此方法构建key(转str)
     */
    @Bean
    public KeyGenerator wiselyKeyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                // sb.append(target.getClass().getName());
                // sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

}
